﻿using System;
using System.Collections.Generic;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace cstdx.Internal;


public static class ZlibCompressor
{
	/// <summary>
	/// 使用zlib算法压缩字节数组
	/// </summary>
	/// <param name="src">要压缩的原始字节数组</param>
	/// <returns>压缩后的字节数组</returns>
	/// <exception cref="ArgumentNullException">当输入字节数组为null时抛出</exception>
	public static byte[] ZlibCompress(byte[] src)
	{
		if (src == null)
			throw new ArgumentNullException(nameof(src));

		using (var outputStream = new MemoryStream())
		{
			// 使用ZlibStream进行压缩，CompressionMode.Compress表示压缩模式
			using (var zlibStream = new ZLibStream(outputStream, CompressionMode.Compress))
			{
				zlibStream.Write(src, 0, src.Length);
			}
			return outputStream.ToArray();
		}
	}

	/// <summary>
	/// 使用zlib算法解压缩字节数组
	/// </summary>
	/// <param name="compressSrc">要解压缩的字节数组</param>
	/// <returns>解压缩后的原始字节数组</returns>
	/// <exception cref="ArgumentNullException">当输入字节数组为null时抛出</exception>
	public static byte[] ZlibUnCompress(byte[] compressSrc)
	{
		if (compressSrc == null)
			throw new ArgumentNullException(nameof(compressSrc));

		using (var inputStream = new MemoryStream(compressSrc))
		using (var zlibStream = new ZLibStream(inputStream, CompressionMode.Decompress))
		using (var outputStream = new MemoryStream())
		{
			zlibStream.CopyTo(outputStream);
			return outputStream.ToArray();
		}
	}
}


